package Practice1_Collection.P11_Stack.P2;

import java.util.*;

public class SuffixExpression {
    Deque<String> stack;

    int execute() {
        Deque<String> temp = new LinkedList<>();
        while (stack.size() > 0) {
            String nS = stack.pop();
            if (nS.matches("\\d+")) {
                temp.push(nS);
            } else if (nS.matches("[\\+\\-\\*/]")) {
                String num2 = temp.pop();
                String num1 = temp.pop();
                temp.push(operation(num1, nS, num2));
            }
        }
        return Integer.parseInt(temp.pop());
    }

    int execute(Map<String,Integer> map) {
        Object[] objects = stack.toArray();
        String[] stackArr = new String[objects.length];
        for (int i = 0; i < objects.length; i++) {
            stackArr[i] = (String)objects[i];
        }
        // 用数字替换未知数
        for (String key : map.keySet()) {
            for (int i = 0; i < stackArr.length; i++) {
                if (stackArr[i].equals(key)) {
                    stackArr[i] = Integer.toString(map.get(key));
                }
            }
        }

        stack = new LinkedList<>();
        for (String s : stackArr) {
            stack.offerLast(s);
        }

        return execute();
    }

    private static String operation(String num1, String sym, String num2) {
        int n1 = Integer.parseInt(num1);
        int n2 = Integer.parseInt(num2);
        int res = 0;
        switch (sym) {
            case "+":
                res = n1 + n2;
                break;
            case "-":
                res = n1 - n2;
                break;
            case "*":
                res = n1 * n2;
                break;
            case "/":
                res = n1 / n2;
                break;
            default:
                break;
        }
        return Integer.toString(res);
    }

    public SuffixExpression(Deque<String> stack) {
        this.stack = stack;
    }
}
